package prome

import (
	"gitee.com/zhucheer/orange/app"
	"github.com/gin-gonic/gin"
	"time"
)

type PromeMiddleware struct {
	PromeHandler *Prometheus
}

func NewPromeMiddleware(p *Prometheus) *PromeMiddleware {
	app.NewHttpHandler(p.MetricsPath, PrometheusHttpHandler())
	return &PromeMiddleware{p}
}

// Func implements Middleware interface.
func (p PromeMiddleware) Func() app.MiddlewareFunc {
	return func(next app.HandlerFunc) app.HandlerFunc {
		return func(c *app.Context) error {
			if c.Request().URL.Path == p.PromeHandler.MetricsPath {
				return next(c)
			}

			c.AddDelayAfterDo(func(ctx *app.Context) {
				p.PromeHandler.reqCnt.WithLabelValues(ctx.Request().Method, ctx.RoutePath()).Inc()
				p.PromeHandler.reqDurSummary.WithLabelValues(ctx.Request().Method, ctx.RoutePath()).Observe(float64(ctx.GetMs().Milliseconds()))
			}, time.Duration(0))

			return next(c)
		}
	}
}

// MiddlewareGinHandlerFunc HandlerFunc defines handler function for middleware
func (p *Prometheus) MiddlewareGinHandlerFunc() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.URL.Path == p.MetricsPath {
			c.Next()
			return
		}

		t := time.Now()

		c.Next()
		t2 := time.Since(t)
		elapsed := t2.Milliseconds()
		p.reqCnt.WithLabelValues(c.Request.Method, c.FullPath()).Inc()
		p.reqDurSummary.WithLabelValues(c.Request.Method, c.FullPath()).Observe(float64(elapsed))
	}
}
